/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: server.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月13日 星期2 16时19分12秒
***************************************************/
//基于基于udp协议开发一个简易时间服务器。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>

struct head
{
	int type;
	char mean[10];
};


struct data
{
	float num1;
	float num2;
};

struct number
{
	float number;
};
int main(int argc,const char* argv[])
{
	int sock = 0;
	int ret = 0;
	char buf[1024] = {0};
	char dest[1024] = {0};

	struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));

	sock = socket(AF_INET,SOCK_DGRAM,0);
	if(sock == -1)
	{
		perror("sock");
		exit(-1);
	}

	addr.sin_family = AF_INET;
        addr.sin_port = htons(6666);
        addr.sin_addr.s_addr = inet_addr("192.168.198.128");

	ret = bind(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind");
		exit(-1);
	}

	struct sockaddr_in cliaddr;
	memset(&cliaddr,0,sizeof(cliaddr));

	int len = sizeof(struct sockaddr);
while(1){
	ret = recvfrom(sock,buf,1024,0,(struct sockaddr *)&cliaddr,&len);
	if(ret == -1)
	{
		perror("recvfrom");
		exit(-1);
	}

	struct head *p = (struct head *)buf;
	struct head hd;
	
		struct data *q = NULL;
		struct number point;
		q = (struct data *)(buf + sizeof(struct head));
		printf("%f\t%f\n",q->num1,q->num2);
		if(p->type == 1)
		{
		point.number = q->num1 + q->num2;
		}

		else if(p->type == 2)
		{
		point.number = q->num1 - q->num2;
		}

		else if(p->type == 3)
		{
		point.number = q->num1 * q->num2;
		}
		else if(p->type == 4)
		{
		point.number = q->num1 / q->num2;
		}
		else if(p->type == 0)
		{
			break;
		}
		memcpy(buf,&hd,sizeof(struct head));
		memcpy(buf + sizeof(struct head),&point,sizeof(struct number));

    		ret = sendto(sock,buf,sizeof(struct head) + sizeof(struct number),0,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr));
		if(ret == -1)
		{
			perror("sendto");
		}
	



}




	close(sock);


    return 0;
}
